<?php
/**
 * SocialEngine
 *
 * @category   Application_Extensions
 * @package    Page
 * @copyright  Copyright Hire-Experts LLC
 * @license    http://www.hire-experts.com
 * @version    $Id: TeamController.php 2010-08-31 16:05 idris $
 * @author     Idris
 */

/**
 * @category   Application_Extensions
 * @package    Page
 * @copyright  Copyright Hire-Experts LLC
 * @license    http://www.hire-experts.com
 */

class Page_TeamController extends Core_Controller_Action_Standard {
	public function init() {
		if (0 !== ($page_id = ( int ) $this->_getParam ( 'page_id' )) && null !== ($page = Engine_Api::_ ()->getItem ( 'page', $page_id ))) {
			Engine_Api::_ ()->core ()->setSubject ( $page );
		}
		
		$this->_helper->requireUser ();
		$this->_helper->requireSubject ( 'page' );
	}
	
	public function removeAction() {
		$page_id = $this->_getParam ( 'page_id' );
		$user_id = $this->_getParam ( 'admin_id' );
		$this->view->form = $form = new Page_Form_Team_Delete ( array ('page_id' => $page_id, 'admin_id' => $user_id ) );
		
		if ($form->isValid ( $form->getValues () ) && $this->getRequest ()->isPost ()) {
			$page = Engine_Api::_ ()->core ()->getSubject ();
			$user = Engine_Api::_ ()->getItem ( 'user', $user_id );
			
			if ($page->user_id != $user->getIdentity ()) {
				$page->getTeamList ()->remove ( $user );
				$page->membership ()->removeMember ( $user );
			}
			
			$this->_redirectCustom ( array ('page_id' => $page_id, 'action' => 'edit', 'route' => 'page_team' ) );
		}
	}
	
	public function ajaxAction() {
		$task = $this->_getParam ( 'task' );
		$page = Engine_Api::_ ()->core ()->getSubject ();
		
		if ($task == 'add_admins') {
			$user_ids = $this->_getParam ( 'user_ids' );
			$list = $page->getTeamList ();
			foreach ( $user_ids as $user_id ) {
				if (! $user_id) {
					continue;
				}
				$user = Engine_Api::_ ()->getItem ( 'user', $user_id );
				
				$page->membership ()->addMember ( $user )->setUserApproved ( $user )->setResourceApproved ( $user );
				$list->add ( $user );
			}
		} elseif ($task == 'change_title') {
			$admin_id = $this->_getParam ( 'admin_id' );
			$title = $this->_getParam ( 'title' );
			
			$user = Engine_Api::_ ()->getItem ( 'user', $admin_id );
			$memberInfo = $page->membership ()->getMemberInfo ( $user );
			$memberInfo->title = $title;
			$memberInfo->save ();
		}
	}

}